package com.example.android_demo01.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android_demo01.R;
import com.example.android_demo01.interfaces.IControl;

import java.util.List;
import java.util.Map;
import java.util.zip.Inflater;

public class MyAdapter extends BaseAdapter {

    /**
     * 数据集和
     */
    List<Map<String, Object>> list;

    /**
     * 布局反射器（布局文件反射未布局对象）
     */
    LayoutInflater inflater;

    IControl control;

    public void setControl(IControl control) {
        this.control = control;
    }

    /**
     * 构造器
     */
    public MyAdapter(Context context){
        this.inflater = LayoutInflater.from(context);
    }

    /**
     * 传入数据集合
     */
    public void setList(List<Map<String, Object>> list){
        this.list = list;
    }


    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if(convertView == null){
            convertView = inflater.inflate(R.layout.item, null);
            holder = new ViewHolder();
            holder.logo = convertView.findViewById(R.id.logo);
            holder.title = convertView.findViewById(R.id.title);
            holder.version = convertView.findViewById(R.id.version);
            holder.size = convertView.findViewById(R.id.size);
            holder.btn = convertView.findViewById(R.id.btn);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        Map<String, Object> map = list.get(position);
        holder.logo.setImageResource((Integer)map.get("logo"));
        holder.title.setText((String)map.get("title"));
        holder.version.setText((String)map.get("version"));
        holder.size.setText((String)map.get("size"));
        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                control.btnClick(position);
            }
        });

        return convertView;
    }

    public static class ViewHolder {
        ImageView logo;
        TextView title;
        TextView version;
        TextView size;
        Button btn;
    }



}
